const Koa = require('koa');
const querystring = require('querystring');
const request = require('request'); // 发送http请求
const Router = require('koa-router');  // 路由中间件
const koaStatic = require('koa-static'); // 静态文件中间件
const session = require('koa-session'); // session 中间件
const cors = require('koa2-cors');  // 跨域
const router = new Router();
router.get('/validCodeMsg', async (ctx, next) => {
    let {phoneNumber} = ctx.request.query;
    if(phoneNumber && /^1[35789]\d{9}$/.test(phoneNumber)){
        function random() {
            return parseInt(Math.random() * 1000000) + '';
        }
        var code = random();
        ctx.session.user = {
            tel: phoneNumber,
            code: code
        };
        var querydata = querystring.stringify({
            mobile: phoneNumber,
            tpl_id: 117376,
            tpl_value: '#code#='+code,
            key: '098612e22e290c18262c3a8b48d7edb5'
        });
        let url = `http://v.juhe.cn/sms/send?${querydata}`;
        let ajax = async (url) => {
            return new Promise((resolve, reject) => {
                request(url, (error, res, body) => {
                    let code = JSON.parse(body);
                    if (code.error_code === 0) {
                        resolve(code)
                    } else {
                        reject(code)
                    }
                })
            })
        };
        await ajax(url).then(() => {
            ctx.body = {
                code: 1,
                msg: '验证码发送成功'
            }
        }).catch(() => {
            ctx.body = {
                code: -1,
                msg: '验证码发送失败'
            }
        })
    }
    await next();
});
router.get('/valid', async (ctx, next) => {
    let {code} = ctx.request.query;
    if (ctx.session.user){
        if (ctx.session.user.code === code) {
            ctx.body = {
                code: 1,
                msg: '注册成功'
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '验证码输入错误'
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请输入手机号'
        }
    }
    await next();
});
const CONFIG = {
    key: 'koa:sess', /** 默认 */
    maxAge: 10000*60*60,  /*  cookie的过期时间        【需要修改】  */
    overwrite: true, /** (boolean) can overwrite or not (default true)    没有效果，默认 */
    httpOnly: true, /**  true表示只有服务器端可以获取cookie */
    signed: true, /** 默认 签名 */
    rolling: true, /** 在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false） 【需要修改】 */
    renew: false, /** (boolean) renew session when session is nearly expired      【需要修改】*/
};
const app = new Koa();
app.keys = ['hello,world!'];
app.use(session(CONFIG, app));
app.use(router.routes());
app.use(koaStatic('./'));
app.listen(8080, () => console.log('the server is running on port 8080'));
